package com.zdya.combatdocuments.filter;

import com.alibaba.fastjson.JSON;
import com.zdya.combatdocuments.entity.vo.ResultEnum;
import com.zdya.combatdocuments.entity.vo.ResultVo;
import com.zdya.combatdocuments.entity.vo.Token;
import com.zdya.combatdocuments.util.JwtUitls;
import com.zdya.combatdocuments.util.ResultVoUtil;
import com.zdya.combatdocuments.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;


@Component
public class LoginFilter implements Filter {

    @Autowired
    private JwtUitls jwtUitls;

    public static final AntPathMatcher PATH_MATCHER= new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

        //定义不需要处理的请求路径
        String[] urls=new String[]{
                "/documents/user/login",
                "/pdf.worker.js",
                "/documents/user/logout",
                "/documents/network/getByPostNet",
                "/documents/network/changeUser",
                "/documents/user/getMacAndCpu",
                "/documents/user/uploadFile",
                "/documents/authorization/applyAuthor",
                "/documents/authorization/acceptAuthorFile",
                "/documents/authorization/acceptAuthor",
                "/documents/authorization/approvalAuthor",
                "/documents/authorization/getAuthorizations",
                "/static/**",
                "/profile/**",
                "/",
                "/css/**",
                "/fonts/**",
                "/img/**",
                "/js/**",
                "/jsmind/**",
                "46b0d77c7e8ed760da95.worker.js/**"
        };
        String url =  ((HttpServletRequest)servletRequest).getRequestURI();
        if(url != null){
            //登录请求直接放行
//            || "/documents/authorization/download".equals(url)
            boolean check=check(urls,url);
            if (check == true){
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            }
//            if("/documents/user/login".equals(url) || url.contains("/profile") || "/".equals(url)){
//                filterChain.doFilter(httpServletRequest,httpServletResponse);
//                return;
//            }
            if ("OPTIONS".equals(httpServletRequest.getMethod())) {
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                //httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                return;
            }
            //其他请求验证token
            String token = httpServletRequest.getHeader("token");
                if(StringUtils.hasText(token)){
                    String token1 = Token.map.get("token");
                    if (token.equals(token1)){
                        //token验证结果
                        int verify  = jwtUitls.verify(token);
                        if(verify != 1){
                            //验证失败
                            if(verify == 2){
                                //说明登录过期  提示重新登录
                                ResultVo result = ResultVoUtil.error(ResultEnum.NEED_LOGIN.getCode(),ResultEnum.NEED_LOGIN.getMessage());
                                WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
                                return;
                            }else if(verify == 0){
                                ResultVo result = ResultVoUtil.error(ResultEnum.USER_ERROR.getCode(),ResultEnum.USER_ERROR.getMessage());
                                WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
                                return;
                            }
                        }else if(verify  == 1){
                            //验证成功，放行
                            filterChain.doFilter(servletRequest,servletResponse);
                            return;
                        }
                    }else {
                        ResultVo result = ResultVoUtil.error(ResultEnum.NEED_LOGIN.getCode(),ResultEnum.NEED_LOGIN.getMessage());
                        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
                        return;
                    }
                    }else {
                        ResultVo result = ResultVoUtil.error(ResultEnum.NEED_LOGIN.getCode(),ResultEnum.NEED_LOGIN.getMessage());
                        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
                        return;
                    }
                }

    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls){
            //判断当前路径与放行的路径是否匹配
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }

}
